<template>
  <div> 
      <template v-if="$attrs.limit == 1 && $attrs.UploadType == 'spec'">
          <el-upload ref="upload" v-bind="$attrs" v-on="$listeners" 
          class="avatar-uploader"
          :action="$attrs.action" 
          :show-file-list="false"
          :auto-upload="$attrs.autoUpload"
          :accept="$attrs.accept"
          :on-preview="handlePictureCardPreview" 
          :on-remove="handleRemove"
          :on-change="handProgress">
          <el-input v-model="fieldValue"  style="width: 70%; float: left; margin-right: 10px;display: none;"></el-input>
          <img v-if="imageUrl.length" :src="unique(imageUrl)[0].url" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </template>
      <template v-else>
          <el-upload ref="upload" v-bind="$attrs" v-on="$listeners" 
          :action="$attrs.action" 
          :multiple="$attrs.multiple" 
          list-type="picture" 
          :auto-upload="$attrs.autoUpload"
          :accept="$attrs.accept"
          :on-preview="handlePictureCardPreview" 
          :on-remove="handleRemove"
          :on-change="handProgress"
          :on-exceed="onExceed"
          :file-list="unique(imageUrl)"
          :limit="$attrs.limit"
          >
           <el-input v-if="fieldValue"  style="display:none;"></el-input>
              <el-input v-model="imagePath"  style="width: 70%; float: left; margin-right: 10px;" @change="setVal"></el-input>

              <el-button slot="trigger" size="medium" type="primary" >{{uploadText}}</el-button>
              <el-button size="medium" type="success" @click="selectPicture">{{selectText}}</el-button>
              <el-progress v-if="percentage > 0" :percentage="percentage" status="success"></el-progress>
              <div slot="tip" class="xdh-form-upload__tip">{{tipText}}</div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" >
              <el-carousel v-if="dialogVisible" :initial-index="imgInx" arrow="always" :autoplay="false" style="height:400px;">
                  <el-carousel-item v-for="item in imageUrl" :key="item.uid"  style="height:400px;">
                  <img style="width:100%;height:100%;" :src="item.url" alt="">
                  </el-carousel-item>
              </el-carousel>
          </el-dialog>
      </template>
        
    </div> 
</template>

<script>
  import * as qiniu from 'qiniu-js'
  import Md5 from 'crypto-js/md5.js';
  import {getQiNiuToken,getQiNiuImagePath,getPrivateImagePath} from '@/api/common';
  export default {
    // inject: ['xdhForm'],
    props: {
      value: {
        type: [String,Number],
        default() {
          return ''
        }
      },
      uploadText: {
        type: String,
        default: '点击上传'
      },
      selectText: {
        type: String,
        default: '选取文件'
      },
      submitText: {
        type: String,
        default: '上传到服务器'
      },
      tipText: {
        type: String,
        default: '只能上传jpg/png文件，且不超过500kb'
      },
      size: {
        type: String
      }
    },
    data(){
      return {
        accept:'',
        imageUrl:[],
        img:'',
        imagePath:'',
        coverId:'',
        dialogVisible:false,
        isPrivate:this.$attrs.isPrivate,
        percentage:0
      }
    },
    computed:  {
      fieldValue: {
        get() {
          this.coverId = this.value ? String(this.value) : '';
          if(this.value) {
            this.getImageUrl();
          }else{
            this.imageUrl = [];
            this.imagePath = '';
          }
          
          // console.log(this.$attrs,this.value,this.$route,'-uplode-------------')
          return this.coverId;
        },
        set(val) {
         
          // this.$emit('input', val)
        }
      }
    },
    methods: {
      //删除
      handleRemove(file,fileList){
        let newPath = [];
        let newCoverId = [];

        for(var i in fileList) {
            newPath.push(fileList[i].path);
            newCoverId.push(fileList[i].cover_id);
        }


        this.imagePath = newPath.join(',');
        this.coverId = newCoverId.join(',');

        this.imageUrl = fileList;

        this.$emit('input', this.coverId);

      },
      async getToken (file,callback){
        // console.log(this.$attrs);
        let params = { 
            filename: file.name,
            type:file.raw.type,
            size:file.raw.size,
            is_private:this.$attrs.isPrivate
        };
        const res =  await getQiNiuToken(params);
        if(res.code == 200) {
          return callback(res.data,true);
        }
        this.assemblingParam(res);
        return callback(res.data,false);
        
      },
      onExceed(files, fileList){
        this.$message({
          message: '最多只能上传'+this.$attrs.limit+'张',
          type: 'error'
        });
        return false;
      },
      //上传
      handProgress(file, list){
        let that = this;
        this.getToken(file,function(res,state){
            if(!state) {
              return false;
            }
             
            that.token = res.token;
            that.hostUrl = res.hostUrl;
           
            let key = file.name+(new Date().getTime());
            let token = res.token;
            let putExtra = {};
            let config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                retryCount: 6,
                region: qiniu.region.z2
            };
            
            const observable = qiniu.upload(file.raw, key, token, putExtra, config);

            
            const subscription = observable.subscribe({
                next:function(res){
                    
                    if(res.total.percent == 100) {
                        that.percentage = 0;
                    }else{
                        that.percentage = res.total.percent;
                    }
                },
                error:function(res) {
                    console.log(res)
                },
                complete:function(res){
                  // console.log(res,'七牛返回')
                    var fileArr = {
                      'img_path' : that.hostUrl+'/'+res.key,
                      'name' : file.raw.name,
                      'is_private':that.$attrs.isPrivate,
                      'path':res.key,
                      'hash':res.hash,
                      'host':that.hostUrl,
                      'type':file.raw.type,
                      'size':file.raw.size,
                      'route':that.$route.path
                    };
                    that.percentage = 0;
                    that.getImagePath(fileArr);
                }
            })
        });

      },
      getImagePath:async function(obj){
        const res =  await getQiNiuImagePath(obj);
        if(res.code == 200) {
            this.assemblingParam(res,obj.name);
        }
        
      },
      assemblingParam(res,filename){
        if(this.$attrs.limit == 1 && this.$attrs.UploadType == 'spec') {
          this.imagePath = res.data.path;
          this.coverId = res.data.cover_id;
          this.imageUrl[0] = res.data;
          this.$refs.upload.clearFiles();
        }else{
          var newPath = this.imagePath ? this.imagePath.split(',') : [];
          var newCoverId = this.coverId ? this.coverId.split(',') : [];

          newPath.push(res.data.path);

          newCoverId.push(res.data.cover_id);

          this.imagePath = newPath.join(',');

          this.coverId = newCoverId.join(',');


          if(filename) {
            res.data.name = filename;
          }
         
        }

        this.imageUrl.push(res.data);
// console.log(this.coverId)
        this.$emit('input', this.coverId);
        
          
          
      },
      unique(newarr) {
        const res = new Map();
        return newarr.filter((arr) => !res.has(arr.path) && res.set(arr.path, 1));
      },
      //查看图片
      handlePictureCardPreview(file) {
          var that = this;
          this.imageUrl.forEach((item,inx)=>{
              if(item.name == file.name) {
                  that.imgInx = inx;
              }
          })
          this.dialogVisible = true;
      },
      async selectPicture(){

      },
      async getImageUrl() {
        this.imageUrl = [];
        var ids = this.coverId.split(',');
        const res =  await getPrivateImagePath({ids:ids});
        if(res.code == 200) {
          
          this.imagePath = res.data.path.join(',');
          res.data.url.forEach((item,inx)=>{
              var arr = res.data.path[inx].split('/');
              var obj= {
                url:item,
                path:res.data.path[inx],
                cover_id:res.data.cover_id[inx],
                name:arr[arr.length-1]
              }
              this.imageUrl.push(obj);
          })
        }
      },
      setVal(){
        var newPath =this.imagePath.split(',');
        if(newPath.length > 1) {
           for(var i in newPath) {
            var obj = {
                  img_path:newPath[i],
                  path:newPath[i],
                  name:Md5(newPath[i]).toString(),
                  type:1,
                  is_private:0
              };
            this.getImagePath(obj);
          }
        }else{
          var obj = {
                  img_path:newPath[0],
                  path:newPath[0],
                  name:Md5(newPath[0]).toString(),
                  type:1,
                  is_private:0
              };
            this.getImagePath(obj);
        }
         
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>